import { build } from 'esbuild';
import { writeFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Bundle the iframe code directly from the iframe-entry.js file
try {
  const result = await build({
    entryPoints: [join(__dirname, 'iframe-entry.js')],
    bundle: true,
    write: false,
    format: 'iife',
    platform: 'browser',
    target: 'es2020',
    minify: false, // Keep readable for debugging
  });

  const bundledCode = result.outputFiles[0].text;

  // Generate the iframe source with the bundled code
  const iframeSrcDoc = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <div id="root"></div>
  <script>
${bundledCode}
  </script>
</body>
</html>
`.trim();

  // Write the bundled iframe source to a TypeScript file
  const outputContent = `// This file is auto-generated by scripts/bundle-iframe.js
// Do not edit directly - modify scripts/iframe-entry.js instead

export const IFRAME_SRC_DOC = \`${iframeSrcDoc.replace(/`/g, '\\`').replace(/\${/g, '\\${')}\`;
`;

  writeFileSync(join(__dirname, '..', 'src', 'remote-dom', 'iframe-bundle.ts'), outputContent);
  console.log('✅ Successfully bundled iframe source with @remote-dom/core');
} catch (error) {
  console.error('❌ Failed to bundle iframe source:', error);
  process.exit(1);
}
